package cn.etynit.service.impl;

import cn.etynit.domain.MovieTicket;
import cn.etynit.domain.UserMovie;
import cn.etynit.exception.GlobalExceptionCodeEnum;
import cn.etynit.mapper.MovieTicketMapper;
import cn.etynit.result.JsonResult;
import cn.etynit.service.IMovieTicketService;
import cn.etynit.service.IUserMovieService;
import cn.etynit.util.AssertUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Wrapper;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author etyn
 * @since 2022-11-24
 */
@Service
public class MovieTicketServiceImpl extends ServiceImpl<MovieTicketMapper, MovieTicket> implements IMovieTicketService {

    @Autowired
    private IUserMovieService userMovieService;


    /**
     * 买电影票
     * @param movieId
     * @param count
     * @return
     */
    @Override
    public JsonResult byMovie(Long movieId, Long count) {
        // 扣减库存
        deductionsStock(movieId, count);
        // 添加用户电影中间表
        EntityWrapper<UserMovie> wrapper = new EntityWrapper<>();
        // user写死
        wrapper.eq("user_id ",1L);
        // 电影id
        wrapper.eq("movie_ticket_id",movieId);
        UserMovie selectUserMovie = userMovieService.selectOne(wrapper);
        // 通过获取到的wrapper去查表中是否有购买的记录，获取到userMovie对象
        // 如果是空就添加，不是空就添加购买的电影票数量
        if (selectUserMovie == null){
            UserMovie userMovie = new UserMovie();
            userMovie.setUserId(1L);
            userMovie.setMovieTicketId(movieId);
            userMovie.setCount(count);
            userMovieService.insert(userMovie);
        } else {
            selectUserMovie.setCount(selectUserMovie.getCount() + count);
            userMovieService.updateById(selectUserMovie);
        }
        return JsonResult.success();
    }



    /**
     * 送电影票
     * @param movieId
     * @param count
     * @param userId
     * @return
     */
    @Override
    public JsonResult giving(Long movieId, Long count, Long userId) {
        // 扣减库存
        deductionsStock(movieId,count);
        // 保存中间表
        UserMovie userMovie = new UserMovie();
        userMovie.setUserId(userId);
        userMovie.setCount(count);
        userMovie.setMovieTicketId(movieId);
        userMovieService.insert(userMovie);
        return JsonResult.success("赠送成功！");
    }




    /**
     * 扣减库存
     * @param movieId
     * @param count
     */
    private void deductionsStock(Long movieId, Long count) {
        // 通过电影id获取到该电影，为空就抛异常
        MovieTicket movieTicket = selectById(movieId);
        AssertUtil.isNotNull(movieTicket, GlobalExceptionCodeEnum.ERROR);
        // 购买成功减去购买票数
        movieTicket.setStock(movieTicket.getStock() - count);
        // 更新
        updateById(movieTicket);
    }
}
